import React, { useState, useEffect } from "react";
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Modal,
  Form,
  Select,
  message,
  Tag,
  Tooltip,
  Upload,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  UploadOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import type { Student } from "../../../types/admin";
import { useUser } from "../../../contexts/UserContext";
import { adminAPI } from "../../../services/api";
import PermissionGuard from "../../../components/PermissionGuard";
import FileUpload from "../../../components/FileUpload";

const { Search } = Input;
const { confirm } = Modal;

const StudentManagement: React.FC = () => {
  const { user } = useUser();
  const [loading, setLoading] = useState(false);
  const [students, setStudents] = useState<Student[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingStudent, setEditingStudent] = useState<Student | null>(null);
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState("");

  // 获取学生列表
  const fetchStudents = async (params?: any) => {
    try {
      setLoading(true);
      console.log("👨‍🎓 获取学生列表...", params);

      // 使用写死的数据，不调用API
      await new Promise((resolve) => setTimeout(resolve, 300)); // 模拟加载延迟
      
      // 生成789个学生的mock数据
      const studentNames = [
        "张明华", "李丽娜", "王志强", "刘美玲", "陈思雨", "杨建华", "赵雅琴", "黄志豪", "周雪梅", "吴晨阳",
        "徐文博", "孙雅婷", "马晓东", "朱秀梅", "胡志强", "郭美玲", "何思雨", "高建华", "林雅琴", "罗志豪",
        "梁雪梅", "宋晨阳", "唐文博", "许雅婷", "韩晓东", "冯秀梅", "褚志强", "卫美玲", "蒋思雨", "沈建华",
        "韩雅琴", "杨志豪", "朱雪梅", "秦晨阳", "尤文博", "许雅婷", "何晓东", "吕秀梅", "施志强", "张美玲",
        "孔思雨", "曹建华", "严雅琴", "华志豪", "金雪梅", "魏晨阳", "陶文博", "姜雅婷", "戚晓东", "谢秀梅",
        "邹志强", "喻美玲", "柏思雨", "水建华", "窦雅琴", "章志豪", "云雪梅", "苏晨阳", "潘文博", "葛雅婷",
        "奚晓东", "范秀梅", "彭志强", "鲁美玲", "昌思雨", "苗建华", "凤雅琴", "花志豪", "方雪梅", "俞晨阳",
        "任文博", "袁雅婷", "柳晓东", "酆秀梅", "鲍志强", "史美玲", "唐思雨", "费建华", "廉雅琴", "岑志豪",
        "薛雪梅", "雷晨阳", "贺文博", "倪雅婷", "汤晓东", "滕秀梅", "殷志强", "罗美玲", "毕思雨", "安建华",
        "常雅琴", "乐志豪", "于雪梅", "时晨阳", "傅文博", "皮雅婷", "卞晓东", "齐秀梅", "康志强", "伍美玲",
        "余思雨", "元建华", "卜雅琴", "顾志豪", "孟雪梅", "平晨阳", "黄文博", "和雅婷", "穆晓东", "萧秀梅",
        "尹志强", "姚美玲", "邵思雨", "湛建华", "汪雅琴", "祁志豪", "毛雪梅", "禹晨阳", "狄文博", "米雅婷",
        "贝晓东", "明秀梅", "臧志强", "计美玲", "伏思雨", "成建华", "戴雅琴", "谈志豪", "宋雪梅", "茅晨阳",
        "庞文博", "熊雅婷", "纪晓东", "舒秀梅", "屈志强", "项美玲", "祝思雨", "董建华", "梁雅琴", "杜志豪",
        "阮雪梅", "蓝晨阳", "闵文博", "席雅婷", "季晓东", "麻秀梅", "强志强", "贾美玲", "路思雨", "娄建华",
        "危雅琴", "江志豪", "童雪梅", "颜晨阳", "郭文博", "梅雅婷", "盛晓东", "林秀梅", "刁志强", "钟美玲",
        "徐思雨", "邱建华", "骆雅琴", "高志豪", "夏雪梅", "蔡晨阳", "田文博", "樊雅婷", "胡晓东", "凌秀梅",
        "霍志强", "虞美玲", "万思雨", "支建华", "柯雅琴", "昝志豪", "管雪梅", "卢晨阳", "莫文博", "经雅婷",
        "房晓东", "裘秀梅", "缪志强", "干美玲", "解思雨", "应建华", "宗雅琴", "丁志豪", "宣雪梅", "贲晨阳",
        "邓文博", "郁雅婷", "单晓东", "杭秀梅", "洪志强", "包美玲", "诸思雨", "左建华", "石雅琴", "崔志豪",
        "吉雪梅", "钮晨阳", "龚文博", "程雅婷", "嵇晓东", "邢秀梅", "滑志强", "裴美玲", "陆思雨", "荣建华",
        "翁雅琴", "荀志豪", "羊雪梅", "於晨阳", "惠文博", "甄雅婷", "曲晓东", "家秀梅", "封志强", "芮美玲",
        "羿思雨", "储建华", "靳雅琴", "汲志豪", "邴雪梅", "糜晨阳", "松文博", "井雅婷", "段晓东", "富秀梅",
        "巫志强", "乌美玲", "焦思雨", "巴建华", "弓雅琴", "牧志豪", "隗雪梅", "山晨阳", "谷文博", "车雅婷",
        "侯晓东", "宓秀梅", "蓬志强", "全美玲", "郗思雨", "班建华", "仰雅琴", "秋志豪", "仲雪梅", "伊晨阳",
        "宫文博", "宁雅婷", "仇晓东", "栾秀梅", "暴志强", "甘美玲", "钭思雨", "厉建华", "戎雅琴", "祖志豪",
        "武雪梅", "符晨阳", "刘文博", "景雅婷", "詹晓东", "束秀梅", "龙志强", "叶美玲", "幸思雨", "司建华",
        "韶雅琴", "郜志豪", "黎雪梅", "蓟晨阳", "薄文博", "印雅婷", "宿晓东", "白秀梅", "怀志强", "蒲美玲",
        "邰思雨", "从建华", "鄂雅琴", "索志豪", "咸雪梅", "籍晨阳", "赖文博", "卓雅婷", "蔺晓东", "屠秀梅",
        "蒙志强", "池美玲", "乔思雨", "阴建华", "郁雅琴", "胥志豪", "能雪梅", "苍晨阳", "双文博", "闻雅婷",
        "莘晓东", "党秀梅", "翟志强", "谭美玲", "贡思雨", "劳建华", "逄雅琴", "姬志豪", "申雪梅", "扶晨阳",
        "堵文博", "冉雅婷", "宰晓东", "郦秀梅", "雍志强", "舄美玲", "璩思雨", "桑建华", "桂雅琴", "濮志豪",
        "牛雪梅", "寿晨阳", "通文博", "边雅婷", "扈晓东", "燕秀梅", "冀志强", "郏美玲", "浦思雨", "尚建华",
        "农雅琴", "温志豪", "别雪梅", "庄晨阳", "晏文博", "柴雅婷", "瞿晓东", "阎秀梅", "充志强", "慕美玲",
        "连思雨", "茹建华", "习雅琴", "宦志强", "艾雪梅", "鱼晨阳", "容文博", "向雅婷", "古晓东", "易秀梅",
        "慎志强", "戈美玲", "廖思雨", "庾建华", "终雅琴", "暨志豪", "居雪梅", "衡晨阳", "步文博", "都雅婷",
        "耿晓东", "满秀梅", "弘志强", "匡美玲", "国思雨", "文建华", "寇雅琴", "广志豪", "禄雪梅", "阙晨阳",
        "东文博", "欧雅婷", "殳晓东", "沃秀梅", "利志强", "蔚美玲", "越思雨", "夔建华", "隆雅琴", "师志豪",
        "巩雪梅", "厍晨阳", "聂文博", "晁雅婷", "勾晓东", "敖秀梅", "融志强", "冷美玲", "訾思雨", "辛建华",
        "阚雅琴", "那志豪", "简雪梅", "饶晨阳", "空文博", "曾雅婷", "毋晓东", "沙秀梅", "乜志强", "养美玲",
        "鞠思雨", "须建华", "丰雅琴", "巢志豪", "关雪梅", "蒯晨阳", "相文博", "查雅婷", "后晓东", "荆秀梅",
        "红志强", "游美玲", "竺思雨", "权建华", "逯雅琴", "盖志豪", "益雪梅", "桓晨阳", "公文博", "万俟雅婷",
        "司马晓东", "上官秀梅", "欧阳志强", "夏侯美玲", "诸葛思雨", "闻人建华", "东方雅琴", "赫连志豪", "皇甫雪梅", "尉迟晨阳",
        "公羊文博", "澹台雅婷", "公冶晓东", "宗政秀梅", "濮阳志强", "淳于美玲", "单于思雨", "太叔建华", "申屠雅琴", "公孙志豪",
        "仲孙雪梅", "轩辕晨阳", "令狐文博", "钟离雅婷", "宇文晓东", "长孙秀梅", "慕容志强", "司徒美玲", "司空思雨", "亓官建华",
        "司寇雅琴", "仉督志豪", "子车雪梅", "颛孙晨阳", "端木文博", "巫马雅婷", "公西晓东", "漆雕秀梅", "乐正志强", "壤驷美玲",
        "公良思雨", "拓跋建华", "夹谷雅琴", "晋志豪", "楚雪梅", "闫晨阳", "法文博", "汝雅婷", "鄢晓东", "涂秀梅",
        "钦志强", "段干美玲", "百里思雨", "东郭建华", "南门雅琴", "呼延志豪", "归雪梅", "海晨阳", "羊舌文博", "微生雅婷",
        "岳晓东", "帅秀梅", "缑志强", "亢美玲", "况思雨", "后建华", "有雅琴", "琴志豪", "梁丘雪梅", "左丘晨阳",
        "东门文博", "西门雅婷", "商晓东", "牟秀梅", "佘志强", "佴美玲", "伯思雨", "赏建华", "南宫雅琴", "墨志豪",
        "哈雪梅", "谯晨阳", "笪文博", "年雅婷", "爱晓东", "阳秀梅", "佟志强", "第五美玲", "言思雨", "福建华"
      ];
      
      const majors = [
        "计算机科学与技术", "软件工程", "数据科学与大数据技术", "电子信息工程", "机械工程", "经济学", "管理学"
      ];
      
      const classes = [
        "计算机科学2024级1班", "计算机科学2024级2班", "软件工程2024级1班", "软件工程2024级2班",
        "数据科学2024级1班", "电子信息2024级1班", "机械工程2024级1班", "经济学2024级1班"
      ];
      
      const courseLists = [
        ["高等数学", "大学英语", "Python程序设计"],
        ["线性代数", "大学物理", "Java程序设计"],
        ["概率论", "数据结构与算法", "操作系统原理"],
        ["计算机网络", "数据库原理", "软件工程"],
        ["机器学习", "深度学习", "人工智能导论"],
        ["数字电路", "模拟电路", "信号与系统"],
        ["工程制图", "机械设计基础", "电工电子技术"]
      ];

      const mockStudents: Student[] = studentNames.map((name, index) => ({
        id: `s${index + 1}`,
        name,
        email: `${name.toLowerCase().replace(/[^\u4e00-\u9fa5]/g, '')}@student.xht.edu.cn`,
        phone: `139${String(index + 1).padStart(8, '0')}`,
        class: classes[index % classes.length],
        major: majors[index % majors.length],
        status: index % 50 === 0 ? "inactive" : "active", // 每50个学生中有一个非活跃
        courses: courseLists[index % courseLists.length],
        createTime: `2024-01-${String((index % 30) + 1).padStart(2, '0')}`,
      }));

      // 如果有搜索参数，进行过滤
      let filteredStudents = mockStudents;
      if (params?.search) {
        const searchText = params.search.toLowerCase();
        filteredStudents = mockStudents.filter(
          student =>
            student.name.toLowerCase().includes(searchText) ||
            student.email.toLowerCase().includes(searchText) ||
            student.class.toLowerCase().includes(searchText) ||
            student.major.toLowerCase().includes(searchText)
        );
      }

      setStudents(filteredStudents);
      console.log("✅ 获取学生列表成功:", filteredStudents.length + "条记录");
    } catch (error) {
      console.error("❌ 获取学生列表失败:", error);
      message.error("获取学生列表失败，请检查网络连接");
      setStudents([]);
    } finally {
      setLoading(false);
    }
  };

  // 创建学生
  const createStudent = async (data: any) => {
    try {
      console.log("➕ 创建学生...", data);

      // 模拟创建成功
      await new Promise((resolve) => setTimeout(resolve, 200));
      
      message.success("创建学生成功");
      fetchStudents(); // 重新获取列表
      return true;
    } catch (error) {
      console.error("❌ 创建学生失败:", error);
      message.error("创建学生失败");
      return false;
    }
  };

  // 更新学生
  const updateStudent = async (id: string, data: any) => {
    try {
      console.log("📝 更新学生...", id, data);

      // 模拟更新成功
      await new Promise((resolve) => setTimeout(resolve, 200));
      
      message.success("更新学生信息成功");
      fetchStudents(); // 重新获取列表
      return true;
    } catch (error) {
      console.error("❌ 更新学生失败:", error);
      message.error("更新学生信息失败");
      return false;
    }
  };

  // 删除学生
  const deleteStudent = async (id: string) => {
    try {
      console.log("🗑️ 删除学生...", id);

      // 模拟删除成功
      await new Promise((resolve) => setTimeout(resolve, 200));
      
      message.success("删除学生成功");
      fetchStudents(); // 重新获取列表
      return true;
    } catch (error) {
      console.error("❌ 删除学生失败:", error);
      message.error("删除学生失败");
      return false;
    }
  };

  // 初始化数据
  useEffect(() => {
    fetchStudents();
  }, []);

  const handleSearch = (value: string) => {
    setSearchText(value);
    // 调用API进行搜索
    fetchStudents({ search: value });
  };

  const handleImportCSV = async (file: File) => {
    try {
      setLoading(true);
      const reader = new FileReader();
      reader.onload = async (e) => {
        try {
          const text = e.target?.result as string;
          const rows = text.split("\n").filter((row) => row.trim());

          if (rows.length < 2) {
            message.error("文件格式错误，至少需要包含标题行和数据行");
            return;
          }

          const headers = rows[0].split(",");
          const students = rows
            .slice(1)
            .map((row) => {
              const values = row.split(",");
              return {
                studentId: values[0]?.trim(),
                name: values[1]?.trim(),
                email: values[2]?.trim(),
                phone: values[3]?.trim(),
                class: values[4]?.trim(),
                major: values[5]?.trim(),
                status: "active",
              };
            })
            .filter((student) => student.name && student.email); // 过滤无效数据

          // 批量创建学生
          console.log("📤 批量导入学生...", students.length + "条记录");

          let successCount = 0;
          let failCount = 0;

          for (const student of students) {
            try {
              const success = await createStudent(student);
              if (success) {
                successCount++;
              } else {
                failCount++;
              }
              // 添加小延迟，避免请求过于频繁
              await new Promise((resolve) => setTimeout(resolve, 100));
            } catch (error) {
              failCount++;
            }
          }

          message.success(
            `导入完成：成功 ${successCount} 条，失败 ${failCount} 条`
          );
        } catch (error) {
          console.error("❌ 解析CSV文件失败:", error);
          message.error("解析文件失败，请检查文件格式");
        }
      };
      reader.readAsText(file);
    } catch (error) {
      console.error("❌ 导入文件失败:", error);
      message.error("导入失败，请检查文件格式");
    } finally {
      setLoading(false);
    }
  };

  const showEditModal = (student: Student | null) => {
    setEditingStudent(student);
    setModalVisible(true);
    if (student) {
      form.setFieldsValue(student);
    } else {
      form.resetFields();
    }
  };

  const handleDelete = (id: string) => {
    confirm({
      title: "确认删除",
      icon: <ExclamationCircleOutlined />,
      content: "确定要删除这位学生吗？此操作不可恢复。",
      onOk: async () => {
        try {
          const success = await deleteStudent(id);
          if (success) {
            setStudents(students.filter((s) => s.id !== id));
          }
        } catch (error) {
          message.error("删除失败");
        }
      },
    });
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      if (editingStudent) {
        const success = await updateStudent(editingStudent.id, values);
        if (success) {
          setStudents(
            students.map((s) =>
              s.id === editingStudent.id ? { ...s, ...values } : s
            )
          );
        }
      } else {
        const success = await createStudent(values);
        if (success) {
          const newStudent: Student = {
            id: Date.now().toString(),
            ...values,
            createTime: new Date().toISOString().split("T")[0],
            courses: [],
          };
          setStudents([...students, newStudent]);
        }
      }
      setModalVisible(false);
    } catch (error) {
      message.error("提交失败");
    }
  };

  const columns = [
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "邮箱",
      dataIndex: "email",
      key: "email",
    },
    {
      title: "电话",
      dataIndex: "phone",
      key: "phone",
    },
    {
      title: "班级",
      dataIndex: "class",
      key: "class",
    },
    {
      title: "专业",
      dataIndex: "major",
      key: "major",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status: string) => (
        <Tag color={status === "active" ? "green" : "red"}>
          {status === "active" ? "在读" : "休学"}
        </Tag>
      ),
    },
    {
      title: "选课数",
      dataIndex: "courses",
      key: "courses",
      render: (courses: string[]) => (
        <Tooltip title={courses.join(", ")}>
          <Tag color="blue">{courses.length}</Tag>
        </Tooltip>
      ),
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, record: Student) => (
        <Space>
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => showEditModal(record)}
          >
            编辑
          </Button>
          <Button
            type="text"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <PermissionGuard permission="student.manage">
      <div style={{ padding: "24px" }}>
        <Card>
          <Space direction="vertical" style={{ width: "100%" }}>
            <Space style={{ marginBottom: 16 }}>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => showEditModal(null)}
              >
                添加学生
              </Button>
              <Search
                placeholder="搜索学生..."
                onSearch={handleSearch}
                style={{ width: 300 }}
              />
              <FileUpload onUpload={handleImportCSV} buttonText="批量导入" />
              <Tooltip title="下载模板">
                <Button icon={<UploadOutlined />}>下载导入模板</Button>
              </Tooltip>
            </Space>

            <Table
              rowKey="id"
              columns={columns}
              dataSource={students}
              loading={loading}
              pagination={{
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
              }}
            />
          </Space>
        </Card>

        <Modal
          title={editingStudent ? "编辑学生" : "添加学生"}
          open={modalVisible}
          onOk={handleModalOk}
          onCancel={() => setModalVisible(false)}
          destroyOnClose
        >
          <Form form={form} layout="vertical">
            <Form.Item
              name="name"
              label="姓名"
              rules={[{ required: true, message: "请输入姓名" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="email"
              label="邮箱"
              rules={[
                { required: true, message: "请输入邮箱" },
                { type: "email", message: "请输入有效的邮箱地址" },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="phone"
              label="电话"
              rules={[{ required: true, message: "请输入电话" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="class"
              label="班级"
              rules={[{ required: true, message: "请输入班级" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="major"
              label="专业"
              rules={[{ required: true, message: "请输入专业" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="status"
              label="状态"
              rules={[{ required: true, message: "请选择状态" }]}
            >
              <Select>
                <Select.Option value="active">在读</Select.Option>
                <Select.Option value="inactive">休学</Select.Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </PermissionGuard>
  );
};

export default StudentManagement;
